function urldecode(str) {
	return decodeURIComponent((str + '')
			.replace(/%(?![\da-f]{2})/gi, function() {return '%25';})
			.replace(/\+/g, '%20'));
}

function insertUpdate(item) {
	var original = $('.item:last').clone();
	
	var descriptionLink = urldecode(item.description_link);
	
	$(original).find('.description-link').val(descriptionLink);
	
	var hideLink = $(original).find('.hide-item-link').attr('href');
	var lastIndex = hideLink.lastIndexOf("/");
	hideLink = hideLink.substr(0, lastIndex);
	$(original).find('.hide-item-link').attr('href', hideLink + '/' + item.id);
	
	var link = $('<a href="' + $(descriptionLink).attr('href')  + '"></a>');
	var img = new Image();
	img.width = 204;
	img.height = 152;
	img.src = $(descriptionLink).find('img').attr('src');
	img.onload = function() {
		$(link).append(img);
		$(original).find('.image').empty().append(link);
	}
	
	$(original).find('.public-date small').empty().text(item.public_date);
	
	$(original).find('.title a').attr('href', urldecode(item.link)).empty().text(urldecode(item.title));
	
	$(original).find('.description-text').empty().text(urldecode(item.description_text));
	
	$(original).find('.read-more').attr('href', urldecode(item.link));
	
	$(original).hide();
	
	$('#main .all').prepend($(original));
	
	$(original).fadeIn();
}

function polling() {
	$.ajax({
		url: pollingUrl +  '?current=' + current + '&noCache=' + (new Date().getTime()), 
		type: 'GET',
		async: true,
		complete: function(response) {
			response = $.parseJSON(response.responseText);
			
			if (response.message.length > 0) {
				$.each(response.message, function(index, value){
					insertUpdate(value);
				})
			}
			
			current = $.trim(response.current) ? $.trim(response.current) : current;
			
			setTimeout(polling, 2000);
		}
	});
}

$(document).ready(function(){
	
	var locked = false;
	var timer = setInterval(function(){
		if (locked) {
			return true;
		}
		
		if ($('.lazy').length == 0) {
			window.clearInterval(timer)
		}
		
		locked = true;
		
		var item = $('.lazy:first');
		var descriptionLink = $(item).find('.description-link').val();
		var image = $(descriptionLink).find('img');
		var link = $('<a href="' + $(descriptionLink).attr('href')  + '"></a>');
		
		var img = new Image();
		img.width = 204;
		img.height = 152;
		
		img.src = $(image).attr('src');
		img.onload = function() {
			$(item).removeClass('lazy');
			$(link).append(img)
			$(item).find('.image').append(link);
			
			locked = false;
		}
		
	}, 100);
	
	$('.remove').live('click', function(){
		var hideUrl = $(this).closest('.item').find('.hide-item-link').attr('href');
		$(this).closest('.item').fadeOut();
		
		$.ajax({
			url: hideUrl,
			complete: function(response) {
				response = $.trim(response.responseText);
				if (response == 'error') {
					alert('Có lỗi xảy ra khi xóa dữ liệu');
				}
			}
		})
	});
	
	if (pollingUrl && current) {
		polling();
	}
})